﻿using System;
using System.Collections.Generic;
using System.Text;
using suce.upload;
using com.byt.webcore;
using System.IO;
using com.byt.suce.db.mapper;
using com.byt.suce.db.factory;
using System.Data.Common;
using MYLSOFT.JsonSimple;
using com.byt.webcore.utils;
using System.Globalization;

namespace com.byt.gestor.service
{
    class GestorToVuce
    {

        private void Format(StringBuilder sb, string format, params object[] args)
        {
            sb.AppendLine(string.Format(format, args));
        }




        public void DGS005_N8(Connection gsuce, int? iddr, string numeorden, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorden, null, null);

            // Borra el EBXML anterior
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));



            PkgEbxml.N8GetParam head = PkgEbxmlFactory.create().newN8GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS005_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS005_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS005_N8_SpecificInformation(sb, head.CurSpecific);
            DGS005_N8_FactoryLocation(sb, head.CurFactory);
            DGS005_N8_StorageLocation(sb, head.CurStorage);
            DGS005_N8_LaboratoryLocation(sb, head.CurLaboratory);
            DGS005_N8_FoodIndustrialProduct(sb, head.CurProducts);
            DGS005_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurPetitioner.Close();
            head.CurSpecific.Close();
            head.CurFactory.Close();
            head.CurStorage.Close();
            head.CurProducts.Close();


            // Comprimir todos los archivos adjuntos sin el xml
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            // Generar el EBXML
            //StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.UTF8);
            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }

        private void DGS005_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS005_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader petitionerTradeParty)
        {
            petitionerTradeParty.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", petitionerTradeParty["NOMB_PERSONA"]);
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", petitionerTradeParty["ID_TIPODOCU"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", petitionerTradeParty["NUME_DOCUMENTO"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", petitionerTradeParty["DIRE_PERSONA"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", petitionerTradeParty["ID_UBIGEO"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", petitionerTradeParty["TELF_FIJO"]);
            Format(sb, "        <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", petitionerTradeParty["TELF_FAX"]);
            Format(sb, "        <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", petitionerTradeParty["REPNOMBPERSONA"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS005_N8_SpecificInformation(StringBuilder sb, DbDataReader specificInformation)
        {
            specificInformation.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", specificInformation["NUME_DR"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", specificInformation["NUM_FILE"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", specificInformation["SUCE_YEAR"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", specificInformation["NUME_SUCE"].ToString().Replace("S",""));
            Format(sb, "        <vram:IssueDate>{0}</vram:IssueDate>", specificInformation["FECH_BROAD"]);
            Format(sb, "        <vram:ExpirationDate>{0}</vram:ExpirationDate>", specificInformation["FECH_VALIDA"]);
            Format(sb, "        <vram:EnrollmentFlag>{0}</vram:EnrollmentFlag>", (specificInformation["reinscripcion"].ToString()=="S") ? "N" : "S" );
            Format(sb, "        <vram:ReEnrollmentFlag>{0}</vram:ReEnrollmentFlag>", (specificInformation["reinscripcion"].ToString()=="S") ? "S" : "N" );
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS005_N8_FactoryLocation(StringBuilder sb, DbDataReader factoryLocation)
        {
            try
            {

                factoryLocation.Read();
                Format(sb, "    <FactoryLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", factoryLocation["DIRE_PERSONA"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "        <vram:TradeCountry>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", factoryLocation["ID_PAIS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PAIS"]);
                Format(sb, "        </vram:TradeCountry>");
                Format(sb, "    </FactoryLocation>");
            }
            catch (Exception)
            {
                
                //throw;
            }
        }

        private void DGS005_N8_StorageLocation(StringBuilder sb, DbDataReader storageLocation)
        {
            try
            {
                storageLocation.Read();
                Format(sb, "    <StorageLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", storageLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:Identification>{0}</vram:Identification>", storageLocation["NUME_DOCUMENTO"]);
                Format(sb, "            <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", storageLocation["DIRE_PERSONA"]);
                Format(sb, "            <vram:Ubigeo>{0}</vram:Ubigeo>", storageLocation["ID_UBIGEO"]);
                Format(sb, "            <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", storageLocation["TELF_FIJO"]);
                Format(sb, "            <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", storageLocation["TELF_FAX"]);
                Format(sb, "            <vram:EmailUniversalCommunication><vram:UniformResourceIdentifier>{0}</vram:UniformResourceIdentifier></vram:EmailUniversalCommunication>", storageLocation["DIRE_EMAIL"]);
                Format(sb, "            <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", storageLocation["REP_NOMB_PERSONA"]);
                Format(sb, "            <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", storageLocation["REP_ID_TIPODOCU"]);
                Format(sb, "            <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", storageLocation["REP_NUME_DOCUMENTO"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "    </StorageLocation>");

            }
            catch (Exception)
            {
                
                //throw;
            }
        }

        private void DGS005_N8_LaboratoryLocation(StringBuilder sb, DbDataReader laboratoryLocation)
        {
            while (laboratoryLocation.Read())
            {
                Format(sb, "    <LaboratoryLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Item>{0}</vram:Item>", laboratoryLocation["ItemLaboratorio"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", laboratoryLocation["nombrelaboratorio"]);
                Format(sb, "            <vram:Identification>{0}</vram:Identification>", laboratoryLocation["idlaboratorio"]);
                Format(sb, "            <vram:Type>{0}</vram:Type>", laboratoryLocation["tipo"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "    </LaboratoryLocation>");
            }
        }

        private void DGS005_N8_FoodIndustrialProduct(StringBuilder sb, DbDataReader products)
        {
            string detalle;
            string[] rowSeparator = new string[] { "<->" };
            string[] colSeparator = new string[] { "]]" };
            string[] rows;
            string[] cols;

            while (products.Read())
            {
                Format(sb, "    <FoodIndustrialProduct>");
                Format(sb, "        <vram:ItemProduct>{0}</vram:ItemProduct>", products["NUME_ITEM"]);
                Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_PRODUCTO"]);
                Format(sb, "        <vram:BrandName><![CDATA[{0}]]></vram:BrandName>", products["MARC_PRODUCTO"]);

                // Composition
                detalle = (string)products["composicion"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:Composition>");
                        Format(sb, "            <vram:ItemComposition>{0}</vram:ItemComposition>", cols[0]);
                        Format(sb, "            <vram:Description><![CDATA[{0}]]></vram:Description>", cols[1]);
                        Format(sb, "        </vram:Composition>");
                    }
                }


                // aditive
                detalle = (string)products["aditivo"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:AdditiveProduct>");
                        Format(sb, "            <vram:ItemAdditive>{0}</vram:ItemAdditive>", cols[0]);
                        Format(sb, "            <vram:TradeName><![CDATA[{0}]]></vram:TradeName>", cols[1]);
                        Format(sb, "            <vram:Weight><![CDATA[{0}]]></vram:Weight>", cols[2]);
                        Format(sb, "            <vram:AlimentaryCode><![CDATA[{0}]]></vram:AlimentaryCode>", cols[3]);
                        Format(sb, "            <vram:GrasSustance><![CDATA[{0}]]></vram:GrasSustance>", cols[4]);
                        Format(sb, "        </vram:AdditiveProduct>");
                    }
                }


                // LogisticsPackage
                detalle = (string)products["envase"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:LogisticsPackage>");
                        Format(sb, "            <vram:ItemPackage>{0}</vram:ItemPackage>", cols[0]);
                        Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", cols[1]);
                        Format(sb, "            <vram:Material><![CDATA[{0}]]></vram:Material>", cols[2]);
                        Format(sb, "            <vram:Capacity><![CDATA[{0}]]></vram:Capacity>", cols[3]);
                        Format(sb, "        </vram:LogisticsPackage>");
                    }
                }

                Format(sb, "        <vram:LifePeriod><![CDATA[{0}]]></vram:LifePeriod>", products["PERI_VIDA"]);
                Format(sb, "        <vram:ProductIdentificationSystem><![CDATA[{0}]]></vram:ProductIdentificationSystem>", products["SIST_LOTE"]);
                /*Format(sb, "        <vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "                <vram:RegisterIdentifier><![CDATA[{0}]]></vram:RegisterIdentifier>", products["AUTO_SANITARIA"]);
                Format(sb, "        </vram:SanitaryRegistryOriginProductRegisterData>");*/
                Format(sb, "        <vram:RegisterCode><![CDATA[{0}]]></vram:RegisterCode>", products["AUTO_SANITARIA"]);
                Format(sb, "        <vram:TradeProduct>");
                Format(sb, "            <vram:TariffCode>{0}</vram:TariffCode>", products["ID_SUBPARTIDA"]);
                Format(sb, "            <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", products["CODI_PARTIDA"]);
                Format(sb, "        </vram:TradeProduct>");
                Format(sb, "        <vram:ProductClassification>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", products["CODI_CLAS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_CLASIFICACION"]);
                Format(sb, "            <vram:Group>{0}</vram:Group>", products["CODI_GRUPO"] == null ? "" : products["CODI_GRUPO"].ToString().Trim());
                Format(sb, "        </vram:ProductClassification>");
                Format(sb, "        ");

                Format(sb, "    </FoodIndustrialProduct>");
            }
        }

        private void DGS005_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }



        public void DGS006_N8(Connection gsuce, int? iddr, string numeorden, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorden, null, null);

            // Borra el EBXML anterior
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));
            
            PkgEbxml.N8dgs006GetParam head = PkgEbxmlFactory.create().newN8dgs006GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8dgs006Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS006_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS006_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS006_N8_SpecificInformation(sb, head.CurSpecific);
            DGS006_N8_FactoryLocation(sb, head.CurFactory);
            DGS006_N8_FoodIndustrialProduct(sb, head.CurProducts);
            DGS006_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurPetitioner.Close();
            head.CurSpecific.Close();
            head.CurFactory.Close();
            //head.CurStorage.Close();
            head.CurProducts.Close();


            // Comprimir todos los archivos adjuntos sin el xml
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            // Generar el EBXML
            //StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.UTF8);
            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));
            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }





        private void DGS006_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS006_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader petitionerTradeParty)
        {
            petitionerTradeParty.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", petitionerTradeParty["NOMB_PERSONA"]);
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", petitionerTradeParty["ID_TIPODOCU"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", petitionerTradeParty["NUME_DOCUMENTO"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", petitionerTradeParty["DIRE_PERSONA"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", petitionerTradeParty["ID_UBIGEO"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", petitionerTradeParty["TELF_FIJO"]);
            Format(sb, "        <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", petitionerTradeParty["TELF_FAX"]);
            Format(sb, "        <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", petitionerTradeParty["REPNOMBPERSONA"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS006_N8_SpecificInformation(StringBuilder sb, DbDataReader specificInformation)
        {
            specificInformation.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", specificInformation["NUME_DR"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", specificInformation["NUM_FILE"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", specificInformation["SUCE_YEAR"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", specificInformation["NUME_SUCE"].ToString().Replace("S", ""));
            Format(sb, "        <vram:IssueDate>{0}</vram:IssueDate>", specificInformation["FECH_BROAD"]);
            Format(sb, "        <vram:ExpirationDate>{0}</vram:ExpirationDate>", specificInformation["FECH_VALIDA"]);
            Format(sb, "        <vram:EnrollmentFlag>{0}</vram:EnrollmentFlag>", (specificInformation["reinscripcion"].ToString() == "S") ? "N" : "S");
            Format(sb, "        <vram:ReEnrollmentFlag>{0}</vram:ReEnrollmentFlag>", (specificInformation["reinscripcion"].ToString() == "S") ? "S" : "N");
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS006_N8_FactoryLocation(StringBuilder sb, DbDataReader factoryLocation)
        {
            try
            {

                factoryLocation.Read();
                Format(sb, "    <FactoryLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:IdentificationType>{0}</vram:IdentificationType>", factoryLocation["ID_TIPODOCU"]);
                Format(sb, "            <vram:Identification>{0}</vram:Identification>", factoryLocation["NUME_DOCUMENTO"]);
                Format(sb, "            <vram:TradeAddress>");
                Format(sb, "                <vram:StreetName><![CDATA[{0}]]></vram:StreetName>", factoryLocation["DIRE_PERSONA"]);
                Format(sb, "            </vram:TradeAddress>");
                Format(sb, "            <vram:Ubigeo>{0}</vram:Ubigeo>", factoryLocation["ID_UBIGEO"]);
                Format(sb, "            <vram:TelephoneUniversalCommunication>");
                Format(sb, "                <vram:CompleteNumber>{0}</vram:CompleteNumber>", factoryLocation["TELF_FIJO"]);
                Format(sb, "            </vram:TelephoneUniversalCommunication>");
                Format(sb, "            <vram:FaxUniversalCommunication>");
                Format(sb, "                <vram:CompleteNumber>{0}</vram:CompleteNumber>", factoryLocation["TELF_FAX"]);
                Format(sb, "            </vram:FaxUniversalCommunication>");
                Format(sb, "            <vram:EmailUniversalCommunication>");
                Format(sb, "                <vram:UniformResourceIdentifier>{0}</vram:UniformResourceIdentifier>", factoryLocation["DIRE_EMAIL"]);
                Format(sb, "            </vram:EmailUniversalCommunication>");
                Format(sb, "            <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", factoryLocation["REP_NOMB_PERSONA"]);
                Format(sb, "            <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", factoryLocation["REP_ID_TIPODOCU"]);
                Format(sb, "            <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", factoryLocation["REP_NUME_DOCUMENTO"]);
                Format(sb, "            <vram:Type>{0}</vram:Type>", factoryLocation["productor"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "    </FactoryLocation>");
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void DGS006_N8_FoodIndustrialProduct(StringBuilder sb, DbDataReader products)
        {
            string detalle;
            string[] rowSeparator = new string[] { "<->" };
            string[] colSeparator = new string[] { "]]" };
            string[] rows;
            string[] cols;

            while (products.Read())
            {
                Format(sb, "    <FoodIndustrialProduct>");
                Format(sb, "        <vram:ItemProduct>{0}</vram:ItemProduct>", products["NUME_ITEM"]);
                Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_PRODUCTO"]);
                Format(sb, "        <vram:BrandName><![CDATA[{0}]]></vram:BrandName>", products["MARC_PRODUCTO"]);
                Format(sb, "        <vram:TradeName><![CDATA[{0}]]></vram:TradeName>", products["Denominacion_Comercial"]);

                // Composition
                detalle = (string)products["composicion"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:Composition>");
                        Format(sb, "            <vram:ItemComposition>{0}</vram:ItemComposition>", cols[0]);
                        Format(sb, "            <vram:Description><![CDATA[{0}]]></vram:Description>", cols[1]);
                        Format(sb, "        </vram:Composition>");
                    }
                }


                // aditive
                detalle = (string)products["aditivo"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:AdditiveProduct>");
                        Format(sb, "            <vram:ItemAdditive>{0}</vram:ItemAdditive>", cols[0]);
                        Format(sb, "            <vram:TradeName><![CDATA[{0}]]></vram:TradeName>", cols[1]);
                        Format(sb, "            <vram:Weight><![CDATA[{0}]]></vram:Weight>", cols[2]);
                        Format(sb, "            <vram:AlimentaryCode><![CDATA[{0}]]></vram:AlimentaryCode>", cols[3]);
                        Format(sb, "            <vram:GrasSustance><![CDATA[{0}]]></vram:GrasSustance>", cols[4]);
                        Format(sb, "        </vram:AdditiveProduct>");
                    }
                }


                // LogisticsPackage
                detalle = (string)products["envase"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:LogisticsPackage>");
                        Format(sb, "            <vram:ItemPackage>{0}</vram:ItemPackage>", cols[0]);
                        Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", cols[1]);
                        Format(sb, "            <vram:Material><![CDATA[{0}]]></vram:Material>", cols[2]);
                        Format(sb, "            <vram:Capacity><![CDATA[{0}]]></vram:Capacity>", cols[3]);
                        Format(sb, "        </vram:LogisticsPackage>");
                    }
                }

                Format(sb, "        <vram:LifePeriod><![CDATA[{0}]]></vram:LifePeriod>", products["PERI_VIDA"]);
                Format(sb, "        <vram:ProductIdentificationSystem><![CDATA[{0}]]></vram:ProductIdentificationSystem>", products["SIST_LOTE"]);
                /*Format(sb, "        <vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "                <vram:RegisterIdentifier><![CDATA[{0}]]></vram:RegisterIdentifier>", products["AUTO_SANITARIA"]);
                Format(sb, "        </vram:SanitaryRegistryOriginProductRegisterData>");*/
                Format(sb, "        <vram:RegisterCode><![CDATA[{0}]]></vram:RegisterCode>", products["AUTO_SANITARIA"]);
                Format(sb, "        <vram:TradeProduct>");
                Format(sb, "            <vram:TariffCode>{0}</vram:TariffCode>", products["ID_SUBPARTIDA"]);
                Format(sb, "            <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", products["CODI_PARTIDA"]);
                Format(sb, "        </vram:TradeProduct>");
                Format(sb, "        <vram:ProductClassification>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", products["CODI_CLAS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_CLASIFICACION"]);
                Format(sb, "            <vram:Group>{0}</vram:Group>", products["CODI_GRUPO"]);
                Format(sb, "        </vram:ProductClassification>");
                Format(sb, "        ");

                Format(sb, "    </FoodIndustrialProduct>");
            }
        }

        private void DGS006_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }


        /* DGS004 CB */

        private void DGS004_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS004_N8_SpecificInformation(StringBuilder sb, DbDataReader SpecificInfo)
        {
            SpecificInfo.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", SpecificInfo["nume_dr"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", SpecificInfo["num_file"]);
            Format(sb, "        <vram:DocumentBroadcastDate>{0}</vram:DocumentBroadcastDate>", SpecificInfo["fech_broad"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", SpecificInfo["suce_year"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", SpecificInfo["nume_suce"]);
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS004_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader Petitioner)
        {
            Petitioner.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", Petitioner["tipodoc"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", Petitioner["nume_documento"]);
            Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", Petitioner["nomb_persona"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName>{0}</vram:StreetName></vram:TradeAddress>", Petitioner["dire_persona"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", Petitioner["id_ubigeo"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", Petitioner["telf_fijo"]);
            Format(sb, "        <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", Petitioner["repretdocu"]);
            Format(sb, "        <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", Petitioner["reprenrodocu"]);
            Format(sb, "        <vram:LegalRepresentativeName>{0}</vram:LegalRepresentativeName>", Petitioner["reprenombpersona"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS004_N8_SanitaryRegisterH(StringBuilder sb, DbDataReader SanitaryRH)
        {
            SanitaryRH.Read();
            Format(sb, "    <SanitaryRegisterHolder>");
            Format(sb, "        <vram:TradeParty><vram:Identification>{0}</vram:Identification></vram:TradeParty>", SanitaryRH["nume_documento"]);
            Format(sb, "        <vram:SanitaryCertificate>");
            Format(sb, "            <vram:FactoryLocation>");
            Format(sb, "                <vram:TradeParty>");
            Format(sb, "                    <vram:Name>{0}</vram:Name>", SanitaryRH["nomb_persona"]);
            Format(sb, "                    <vram:TradeAddress><vram:StreetName>{0}</vram:StreetName></vram:TradeAddress>", SanitaryRH["dire_persona"]);
            Format(sb, "                </vram:TradeParty>");
            Format(sb, "            </vram:FactoryLocation>");
            Format(sb, "        </vram:SanitaryCertificate>");
            Format(sb, "    </SanitaryRegisterHolder>");
        }

        private void DGS004_N8_ProductDestination(StringBuilder sb, DbDataReader ProductDest)
        {
            ProductDest.Read();
            Format(sb, "    <ProductDestination>");
            Format(sb, "        <vram:DestinationTradeCountry>");
            Format(sb, "            <vram:Code>{0}</vram:Code>", ProductDest["pais"]);
            Format(sb, "            <vram:Name>{0}</vram:Name>", ProductDest["nomb_pais"]);
            Format(sb, "        </vram:DestinationTradeCountry>");
            Format(sb, "    </ProductDestination>");
        }

        private void DGS004_N8_SanitaryRegister(StringBuilder sb, DbDataReader SanitaryReg)
        {
            
            while (SanitaryReg.Read())
            {
                Format(sb, "    <SanitaryRegister>");
                Format(sb, "        <vram:ItemSanitaryRegister>{0}</vram:ItemSanitaryRegister>", SanitaryReg["nume_item"]);
                Format(sb, "        <vram:Code>{0}</vram:Code>", SanitaryReg["reg_sanitario"]);
                Format(sb, "        <vram:FoodProduct>");
                Format(sb, "            <vram:Name>{0}</vram:Name>", SanitaryReg["nomb_producto"]);
                Format(sb, "            <vram:Manufacturer>{0}</vram:Manufacturer>", SanitaryReg["fabricante"]);
                Format(sb, "            <vram:TradeProduct>");
                Format(sb, "                <vram:TariffCode>{0}</vram:TariffCode>", SanitaryReg["subparnac"]);
                Format(sb, "                <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", SanitaryReg["coddetpartida"]);
                Format(sb, "                <vram:PhysicalUnit>{0}</vram:PhysicalUnit>", SanitaryReg["um"]);
                Format(sb, "                <vram:PhysicalQuantity>{0}</vram:PhysicalQuantity>", SanitaryReg["CantFis"]);
                Format(sb, "            </vram:TradeProduct>");
                Format(sb, "        </vram:FoodProduct>");
                Format(sb, "        <vram:SanitaryCertificateNumber>{0}</vram:SanitaryCertificateNumber>", SanitaryReg["certificado"]);
                Format(sb, "        <vram:IssueDate>{0}</vram:IssueDate>", SanitaryReg["femision"]);
                Format(sb, "        <vram:ExpirationDate>{0}</vram:ExpirationDate>", SanitaryReg["ffin"]);
                Format(sb, "    </SanitaryRegister>");
            }
        }

        private void DGS004_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }

        /* FIN DE LA MODIFICACION DGS004*/

        /* MODIFICADO POR CESAR BOCANEGRA DGS003 */

        private void DGS003_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS003_N8_SpecificInformation(StringBuilder sb, DbDataReader SpecificInfo)
        {
            SpecificInfo.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", SpecificInfo["nume_dr"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", SpecificInfo["num_file"]);
            Format(sb, "        <vram:DocumentBroadcastDate>{0}</vram:DocumentBroadcastDate>", SpecificInfo["fech_broad"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", SpecificInfo["suce_year"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", SpecificInfo["nume_suce"]);
            Format(sb, "    </SpecificInformation>");

        }

        private void DGS003_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader Petitioner)
        {
            Petitioner.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", Petitioner["id_tipodocu"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", Petitioner["nume_documento"]);
            Format(sb, "        <vram:Name>{0}</vram:Name>", Petitioner["nomb_persona"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName>{0}</vram:StreetName></vram:TradeAddress>", Petitioner["dire_persona"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", Petitioner["id_ubigeo"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", Petitioner["telf_fijo"]);
            Format(sb, "        <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", Petitioner["repidtipodocu"]);
            Format(sb, "        <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", Petitioner["repnrodocu"]);
            Format(sb, "        <vram:LegalRepresentativeName>{0}</vram:LegalRepresentativeName>", Petitioner["repnombpersona"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS003_N8_StorageLocation(StringBuilder sb, DbDataReader Storage)
        {
            Storage.Read();
            Format(sb, "   <StorageLocation>");
            Format(sb, "        <vram:TradeParty>");
            Format(sb, "            <vram:Name>{0}</vram:Name>", Storage["nomb_persona"]);
            Format(sb, "            <vram:Identification>{0}</vram:Identification>", Storage["nume_documento"]);
            Format(sb, "            <vram:TradeAddress><vram:StreetName>{0}</vram:StreetName></vram:TradeAddress>", Storage["dire_persona"]);
            Format(sb, "            <vram:Ubigeo>{0}</vram:Ubigeo>", Storage["id_ubigeo"]);
            Format(sb, "            <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", Storage["telf_fijo"]);
            Format(sb, "            <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", Storage["telf_fax"]);
            Format(sb, "            <vram:EmailUniversalCommunication><vram:UniformResourceIdentifier>{0}</vram:UniformResourceIdentifier></vram:EmailUniversalCommunication>", Storage["dire_email"]);
            Format(sb, "            <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", Storage["rep_id_tipodocu"]);
            Format(sb, "            <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", Storage["rep_nume_documento"]);
            Format(sb, "            <vram:LegalRepresentativeName>{0}</vram:LegalRepresentativeName>", Storage["rep_nomb_persona"]);
            Format(sb, "       </vram:TradeParty>");
            Format(sb, "       <vram:UbigeoDetail>");
            Format(sb, "            <vram:Department><vram:Name>{0}</vram:Name></vram:Department>", Storage["departamento"]);
            Format(sb, "            <vram:Province><vram:Name>{0}</vram:Name></vram:Province>", Storage["provincia"]);
            Format(sb, "            <vram:District><vram:Name>{0}</vram:Name></vram:District>", Storage["distrito"]);
            Format(sb, "       </vram:UbigeoDetail>");
            Format(sb, "    </StorageLocation>");
        }

        private void DGS003_N8_SanitaryRegister(StringBuilder sb, DbDataReader SanitaryRegisterT, DbDataReader SanitaryRegisterR)
        {
            SanitaryRegisterT.Read();
            Format(sb, "    <SanitaryRegisterHolder>");
            Format(sb, "        <vram:TradeParty><vram:Name>{0}</vram:Name></vram:TradeParty>", SanitaryRegisterT["nomb_persona"]);
            Format(sb, "        <vram:OriginTradeCountry><vram:Code>{0}</vram:Code></vram:OriginTradeCountry>", SanitaryRegisterT["id_pais"]);
            Format(sb, "        <vram:OriginTradeCountry><vram:Name>{0}</vram:Name></vram:OriginTradeCountry>", SanitaryRegisterT["nomb_pais"]);
            Format(sb, "        <vram:SanitaryCertificate>");
            Format(sb, "            <vram:Number>{0}</vram:Number>", SanitaryRegisterT["certificado"]);

            while (SanitaryRegisterR.Read())
            {
                Format(sb, "        <vram:SanitaryRegister>");
                Format(sb, "            <vram:ItemSanitaryRegister>{0}</vram:ItemSanitaryRegister>", SanitaryRegisterR["nume_item"]);
                Format(sb, "            <vram:Code>{0}</vram:Code>", SanitaryRegisterR["reg_sanitario"]);
                Format(sb, "            <vram:FoodProduct>");
                Format(sb, "                <vram:Name>{0}</vram:Name>", SanitaryRegisterR["nomb_producto"]);
                Format(sb, "                <vram:BrandName>{0}</vram:BrandName>", SanitaryRegisterR["marc_producto"]);
                Format(sb, "                <vram:UsefulLife>{0}</vram:UsefulLife>", SanitaryRegisterR["peri_vida"]);
                Format(sb, "                <vram:TradeProduct>");
                Format(sb, "                    <vram:TariffCode>{0}</vram:TariffCode>", SanitaryRegisterR["codi_partida"]);
                Format(sb, "                    <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", SanitaryRegisterR["id_subpartida"]);
                Format(sb, "                </vram:TradeProduct>");
                Format(sb, "            </vram:FoodProduct>");
                Format(sb, "            <vram:IssueDate>{0}</vram:IssueDate>", SanitaryRegisterR["femision"]);
                Format(sb, "            <vram:ExpirationDate>{0}</vram:ExpirationDate>", SanitaryRegisterR["ffin"]);
                Format(sb, "        </vram:SanitaryRegister>");
            }

         Format(sb, "       </vram:SanitaryCertificate>");
         Format(sb, "   </SanitaryRegisterHolder>");    
        }

        private void DGS003_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }

        /* FIN DE LA MODIFICACION */ 



        /* MODIFICADO POR CESAR BOCANEGRA */

        private void DGS002_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS002_N8_SpecificInformation(StringBuilder sb, DbDataReader SpecificInfo)
        {
            SpecificInfo.Read(); //se lee el data reader, resultado del cur
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", SpecificInfo["suce_year"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", SpecificInfo["nume_suce"]);
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", SpecificInfo["nume_dr"]);
            Format(sb, "        <vram:DocumentBroadcastDate>{0}</vram:DocumentBroadcastDate>", SpecificInfo["fech_broad"]);
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS002_N8_EstablishmentLocation(StringBuilder sb, DbDataReader Establish)
        {
            Establish.Read();
            Format(sb, "    <EstablishmentLocation>");
            Format(sb, "        <vram:TradeParty>");
            Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", Establish["nomestabl"]);
            Format(sb, "            <vram:TradeAddress>");
            Format(sb, "                <vram:StreetName><![CDATA[{0}]]></vram:StreetName>", Establish["direcestabl"]);
            Format(sb, "            </vram:TradeAddress>");
            Format(sb, "            <vram:Identification>{0}</vram:Identification>", Establish["id_persona"]);
            Format(sb, "        </vram:TradeParty>");
            Format(sb, "    </EstablishmentLocation>");
        }

        private void DGS002_N8_ProductDestination(StringBuilder sb, DbDataReader ProductD)
        {
            ProductD.Read();
            Format(sb, "    <ProductDestination>");
            Format(sb, "        <vram:OriginPort><![CDATA[{0}]]></vram:OriginPort>", ProductD["PTOENVIO"]);
            Format(sb, "        <vram:DestinationPort><![CDATA[{0}]]></vram:DestinationPort>", ProductD["PTODESTINO"]);
            Format(sb, "        <vram:TradeTransportMode>");
            Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", ProductD["TRANSPORTE"]);
            Format(sb, "        </vram:TradeTransportMode>");
            Format(sb, "        <vram:LoadingDate>{0}</vram:LoadingDate>", ProductD["FECHAEMB"]);
            Format(sb, "        <vram:SenderTradeParty>");
            Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", ProductD["nomexped"]);
            Format(sb, "            <vram:TradeAddress>");
            Format(sb, "                <vram:StreetName><![CDATA[{0}]]></vram:StreetName>", ProductD["direcexped"]);
            Format(sb, "            </vram:TradeAddress>");
            Format(sb, "        </vram:SenderTradeParty>");
            Format(sb, "        <vram:ConsigneeTradeParty>");
            Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", ProductD["nomdest"]);
            Format(sb, "            <vram:TradeAddress>");
            Format(sb, "                <vram:StreetName><![CDATA[{0}]]></vram:StreetName>", ProductD["diredest"]);
            Format(sb, "            </vram:TradeAddress>");
            Format(sb, "        </vram:ConsigneeTradeParty>");
            Format(sb, "        <vram:AdditionalNotes><![CDATA[{0}]]></vram:AdditionalNotes>", ProductD["notifadicion"]);
            Format(sb, "    </ProductDestination>");
        }

        private void DGS002_N8_FoodDrink(StringBuilder sb, DbDataReader products)
        {
            while (products.Read())
            {
                Format(sb, "    <FoodDrinkProduct>");
                Format(sb, "        <vram:Description><![CDATA[{0}]]></vram:Description>", products["descripcion"]);
                Format(sb, "        <vram:ScientificName><![CDATA[{0}]]></vram:ScientificName>", products["nomcient"]);
                Format(sb, "        <vram:Type><![CDATA[{0}]]></vram:Type>", products["tipo"]);
                Format(sb, "        <vram:LogisticsPackage>");
                Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", products["embalaje"]);
                Format(sb, "        </vram:LogisticsPackage>");
                Format(sb, "        <vram:ProductFormat><![CDATA[{0}]]></vram:ProductFormat>", products["presentacion"]);
                Format(sb, "        <vram:NetWeight>{0}</vram:NetWeight>", products["pesoneto"]);
                Format(sb, "    </FoodDrinkProduct>");
            }

        }

        private void DGS002_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }

        /* FIN DE MODIFICACION */




        public void DGS008_N8(Connection gsuce, int? iddr, string numeorden, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorden, null, null);

            // Borra el EBXML anterior
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));



            PkgEbxml.N8GetParam head = PkgEbxmlFactory.create().newN8GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS008_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS008_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS008_N8_SpecificInformation(sb, head.CurSpecific);
            DGS008_N8_FactoryLocation(sb, head.CurFactory);
            DGS008_N8_StorageLocation(sb, head.CurStorage);
            DGS008_N8_FoodIndustrialProduct(sb, head.CurProducts);
            DGS008_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurPetitioner.Close();
            head.CurSpecific.Close();
            head.CurFactory.Close();
            head.CurStorage.Close();
            head.CurProducts.Close();


            // Comprimir todos los archivos adjuntos sin el xml
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            // Generar el EBXML
            //StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.UTF8);
            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }

        private void DGS008_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS008_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader petitionerTradeParty)
        {
            petitionerTradeParty.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", petitionerTradeParty["NOMB_PERSONA"]);
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", petitionerTradeParty["ID_TIPODOCU"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", petitionerTradeParty["NUME_DOCUMENTO"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", petitionerTradeParty["DIRE_PERSONA"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", petitionerTradeParty["ID_UBIGEO"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", petitionerTradeParty["TELF_FIJO"]);
            Format(sb, "        <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", petitionerTradeParty["TELF_FAX"]);
            Format(sb, "        <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", petitionerTradeParty["REPNOMBPERSONA"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS008_N8_SpecificInformation(StringBuilder sb, DbDataReader specificInformation)
        {
            specificInformation.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", specificInformation["NUME_DR"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", specificInformation["NUM_FILE"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", specificInformation["SUCE_YEAR"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", specificInformation["NUME_SUCE"].ToString().Replace("S", ""));
            Format(sb, "        <vram:DocumentBroadcastDate>{0}</vram:DocumentBroadcastDate>", specificInformation["FECH_BROAD"]);
            Format(sb, "        <vram:DocumentValidity>{0}</vram:DocumentValidity>", specificInformation["FECH_VALIDA"]);
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS008_N8_FactoryLocation(StringBuilder sb, DbDataReader factoryLocation)
        {
            try
            {

                factoryLocation.Read();
                Format(sb, "    <FactoryLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", factoryLocation["DIRE_PERSONA"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "        <vram:TradeCountry>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", factoryLocation["ID_PAIS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PAIS"]);
                Format(sb, "        </vram:TradeCountry>");
                Format(sb, "    </FactoryLocation>");
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void DGS008_N8_StorageLocation(StringBuilder sb, DbDataReader storageLocation)
        {
            try
            {
                storageLocation.Read();
                Format(sb, "    <StorageLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", storageLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:Identification>{0}</vram:Identification>", storageLocation["NUME_DOCUMENTO"]);
                Format(sb, "            <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", storageLocation["DIRE_PERSONA"]);
                Format(sb, "            <vram:Ubigeo>{0}</vram:Ubigeo>", storageLocation["ID_UBIGEO"]);
                Format(sb, "            <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", storageLocation["TELF_FIJO"]);
                Format(sb, "            <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", storageLocation["TELF_FAX"]);
                Format(sb, "            <vram:EmailUniversalCommunication><vram:UniformResourceIdentifier>{0}</vram:UniformResourceIdentifier></vram:EmailUniversalCommunication>", storageLocation["DIRE_EMAIL"]);
                Format(sb, "            <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", storageLocation["REP_NOMB_PERSONA"]);
                Format(sb, "            <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", storageLocation["REP_ID_TIPODOCU"]);
                Format(sb, "            <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", storageLocation["REP_NUME_DOCUMENTO"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "    </StorageLocation>");

            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void DGS008_N8_FoodIndustrialProduct(StringBuilder sb, DbDataReader products)
        {
            string detalle;
            string[] rowSeparator = new string[] { "<->" };
            string[] colSeparator = new string[] { "]]" };
            string[] rows;
            string[] cols;

            while (products.Read())
            {
                Format(sb, "    <FoodIndustrialProduct>");
                Format(sb, "        <vram:ItemProduct>{0}</vram:ItemProduct>", products["NUME_ITEM"]);
                Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_PRODUCTO"]);
                Format(sb, "        <vram:BrandName><![CDATA[{0}]]></vram:BrandName>", products["MARC_PRODUCTO"]);

                // Composition
                detalle = (string)products["composicion"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:Composition>");
                        Format(sb, "            <vram:ItemComposition>{0}</vram:ItemComposition>", cols[0]);
                        Format(sb, "            <vram:Description><![CDATA[{0}]]></vram:Description>", cols[1]);
                        Format(sb, "        </vram:Composition>");
                    }
                }

                // LogisticsPackage
                detalle = (string)products["envase"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:LogisticsPackage>");
                        Format(sb, "            <vram:ItemPackage>{0}</vram:ItemPackage>", cols[0]);
                        Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", cols[1]);
                        Format(sb, "            <vram:Material><![CDATA[{0}]]></vram:Material>", cols[2]);
                        Format(sb, "            <vram:Capacity><![CDATA[{0}]]></vram:Capacity>", cols[3]);
                        Format(sb, "        </vram:LogisticsPackage>");
                    }
                }

                Format(sb, "        <vram:LifePeriod><![CDATA[{0}]]></vram:LifePeriod>", products["PERI_VIDA"]);
                Format(sb, "        <vram:ProductIdentificationSystem><![CDATA[{0}]]></vram:ProductIdentificationSystem>", products["SIST_LOTE"]);
                Format(sb, "        <vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "                <vram:RegisterIdentifier><![CDATA[{0}]]></vram:RegisterIdentifier>", products["AUTO_SANITARIA"]);
                Format(sb, "        </vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "        <vram:TradeProduct>");
                Format(sb, "            <vram:TariffCode>{0}</vram:TariffCode>", products["ID_SUBPARTIDA"]);
                Format(sb, "            <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", products["CODI_PARTIDA"]);
                Format(sb, "        </vram:TradeProduct>");
                Format(sb, "        <vram:ProductClassification>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", products["CODI_CLAS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_CLASIFICACION"]);
                Format(sb, "            <vram:Group>{0}</vram:Group>", products["CODI_GRUPO"] == null ? "" : products["CODI_GRUPO"].ToString().Trim());
                Format(sb, "        </vram:ProductClassification>");
                Format(sb, "        ");

                Format(sb, "    </FoodIndustrialProduct>");
            }
        }

        private void DGS008_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }

        public void DGS004_N8(Connection gsuce, int? iddr, string numeorder, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            //string folder = "S" + idsolicitud;
            string folder = numeorder.Substring(1,10).ToString() + "\\" + "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorder.Substring(1,10).ToString() + "\\" + numeorder, null, null);

            //si existe un ebxml anterior lo borra
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));

            //encabezado ebxml
            PkgEbxml.N8dgs004GetParam head = PkgEbxmlFactory.create().newN8dgs004GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8dgs004Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS004_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS004_N8_SpecificInformation(sb, head.CurSpecific);
            DGS004_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS004_N8_SanitaryRegisterH(sb, head.CurSanitaryRegisterH);
            DGS004_N8_ProductDestination(sb, head.CurProductDest);
            DGS004_N8_SanitaryRegister(sb, head.CurSanitaryRegister);
            DGS004_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurSpecific.Close();
            head.CurPetitioner.Close();
            head.CurSanitaryRegisterH.Close();
            head.CurProductDest.Close();
            head.CurSanitaryRegister.Close();

            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });


        }



        public void DGS003_N8(Connection gsuce, int? iddr, string numeorder, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorder, null, null);

            //si existe un ebxml anterior lo borra
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));

            //encabezado ebxml
            PkgEbxml.N8dgs003GetParam head = PkgEbxmlFactory.create().newN8dgs003GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8dgs003Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS003_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS003_N8_SpecificInformation(sb, head.CurSpecific);
            DGS003_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS003_N8_StorageLocation(sb, head.CurStorageLocation);
            DGS003_N8_SanitaryRegister(sb, head.CurSanitaryRegisterEs, head.CurSanitaryRegisterPd);
            DGS003_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurPetitioner.Close();
            head.CurSanitaryRegisterEs.Close();
            head.CurSanitaryRegisterPd.Close();
            head.CurSpecific.Close();
            head.CurStorageLocation.Close();

            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }
        /* MODIFICADO POR CESAR BOCANEGRA */

        public void DGS002_N8(Connection gsuce, int? iddr, string numeorder, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            //carpetas
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorder, null, null);

            //si existe un ebxml anterior lo borra
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));

            //encabezado ebxml
            PkgEbxml.N8dgs002GetParam head = PkgEbxmlFactory.create().newN8dgs002GetParam();
            head.Iddr = iddr;
            head.Estado = estadoDr;
            PkgEbxmlFactory.create().n8dgs002Get(gsuce, head);

            StringBuilder sb = new StringBuilder(8192);
            DGS002_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS002_N8_SpecificInformation(sb, head.CurSpecific);
            DGS002_N8_EstablishmentLocation(sb, head.CurEstablishment);
            DGS002_N8_FoodDrink(sb, head.CurFoodDrink);
            DGS002_N8_ProductDestination(sb, head.CurProductDestination);
            DGS002_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");

            head.CurEstablishment.Close();
            head.CurFoodDrink.Close();
            head.CurProductDestination.Close();
            head.CurSpecific.Close();

            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }

        /* FIN DE LA MODIFICACION*/

        public void DGS009_N8(Connection gsuce, int? iddr, string numeorden, int? idsolicitud, decimal? idnotificacion, string estadoDr)
        {
            string folder = "S" + idsolicitud;
            string filterAdjuntos = "DR" + estadoDr + "*.*";
            string path = UploadHelper.GetPath(numeorden, null, null);

            // Borra el EBXML anterior
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));
            File.Delete(Path.Combine(path, idnotificacion + ".zip"));

            //PkgEbxml.N8GetParam head = PkgEbxmlFactory.create().newN8GetParam();
            PkgEbxml.N8dgs009GetParam head = PkgEbxmlFactory.create().newN8dgs009GetParam(); //MODIFICADO POR CESAR BOCANEGRA
            head.Iddr = iddr;
            head.Estado = estadoDr;
            //PkgEbxmlFactory.create().n8Get(gsuce, head);
            PkgEbxmlFactory.create().n8dgs009Get(gsuce, head); //MODIFICADO POR CESAR BOCANEGRA

            StringBuilder sb = new StringBuilder(8192);
            /*
            DGS005_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS005_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS005_N8_SpecificInformation(sb, head.CurSpecific);
            DGS005_N8_FactoryLocation(sb, head.CurFactory);
            DGS005_N8_StorageLocation(sb, head.CurStorage);
            DGS005_N8_FoodIndustrialProduct(sb, head.CurProducts);
            DGS005_N8_AttachedDocument(sb, folder, filterAdjuntos);
*/
//MODIFICADO POR CESAR BOCANEGRA            
            DGS009_N8_InitHeader(sb, head.Xmlns, head.Xsd);
            DGS009_N8_PetitionerTradeParty(sb, head.CurPetitioner);
            DGS009_N8_SpecificInformation(sb, head.CurSpecific);
            DGS009_N8_StorageLocation(sb, head.CurStorage);
            DGS009_N8_FactoryLocation(sb, head.CurFactory);
            DGS009_N8_FoodIndustrialProduct(sb, head.CurProducts);
            DGS009_N8_AttachedDocument(sb, folder, filterAdjuntos);
            sb.AppendLine("</dr>");
//FIN DE LA MODIFICACION            

            head.CurPetitioner.Close();
            head.CurSpecific.Close();
            head.CurFactory.Close();
            head.CurStorage.Close();
            head.CurProducts.Close();
            


            // Comprimir todos los archivos adjuntos sin el xml
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".zip"), UploadHelper.ListFilesStringFullName(folder, filterAdjuntos));

            // Generar el EBXML
            //StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.UTF8);
            StreamWriter sw = new StreamWriter(Path.Combine(path, idnotificacion + ".xml"), false, Encoding.GetEncoding("ISO-8859-1"));

            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }

        private void DGS009_N8_InitHeader(StringBuilder sb, string xmlns, string xsd)
        {
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<dr xmlns=\"urn:peru:vuce:data:standard:{0}:1\" ", xsd);
            sb.AppendLine("    xmlns:vram=\"DigesaDRReusableAggregateBusinessInformationEntity\" ");
            sb.AppendLine("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "    xsi:schemaLocation=\"urn:peru:vuce:data:standard:{0}:1..\\..\\uncefact\\data\\standard\\dr\\{1}.xsd\">", xsd, xsd);
        }

        private void DGS009_N8_PetitionerTradeParty(StringBuilder sb, DbDataReader petitionerTradeParty)
        {
            petitionerTradeParty.Read();
            Format(sb, "    <PetitionerTradeParty>");
            Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", petitionerTradeParty["NOMB_PERSONA"]);
            Format(sb, "        <vram:IdentificationType>{0}</vram:IdentificationType>", petitionerTradeParty["ID_TIPODOCU"]);
            Format(sb, "        <vram:Identification>{0}</vram:Identification>", petitionerTradeParty["NUME_DOCUMENTO"]);
            Format(sb, "        <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", petitionerTradeParty["DIRE_PERSONA"]);
            Format(sb, "        <vram:Ubigeo>{0}</vram:Ubigeo>", petitionerTradeParty["ID_UBIGEO"]);
            Format(sb, "        <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", petitionerTradeParty["TELF_FIJO"]);
            Format(sb, "        <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", petitionerTradeParty["TELF_FAX"]);
            Format(sb, "        <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", petitionerTradeParty["REPNOMBPERSONA"]);
            Format(sb, "    </PetitionerTradeParty>");
        }

        private void DGS009_N8_SpecificInformation(StringBuilder sb, DbDataReader specificInformation)
        {
            specificInformation.Read();
            Format(sb, "    <SpecificInformation>");
            Format(sb, "        <vram:DocumentNumber>{0}</vram:DocumentNumber>", specificInformation["NUME_DR"]);
            Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", specificInformation["NUM_FILE"]);
            Format(sb, "        <vram:OriginalDRYear>{0}</vram:OriginalDRYear>", specificInformation["origanio"]);
            Format(sb, "        <vram:OriginalDRNumber>{0}</vram:OriginalDRNumber>", specificInformation["orignro"]);
            Format(sb, "        <vram:SuceYear>{0}</vram:SuceYear>", specificInformation["SUCE_YEAR"]);
            Format(sb, "        <vram:SuceNumber>{0}</vram:SuceNumber>", specificInformation["NUME_SUCE"].ToString().Replace("S", ""));
            Format(sb, "        <vram:DocumentBroadcastDate>{0}</vram:DocumentBroadcastDate>", specificInformation["FECH_BROAD"]);
            Format(sb, "        <vram:DocumentValidity>{0}</vram:DocumentValidity>", specificInformation["FECH_VALIDA"]);
            Format(sb, "    </SpecificInformation>");
        }

        private void DGS009_N8_FactoryLocation(StringBuilder sb, DbDataReader factoryLocation)
        {
            try
            {

                factoryLocation.Read();
                Format(sb, "    <FactoryLocation>");
                Format(sb, "        <vram:TradeParty>");
                Format(sb, "            <vram:IdentificationType>{0}</vram:IdentificationType>", factoryLocation["ID_TIPODOCU"]);
                Format(sb, "            <vram:Identification>{0}</vram:Identification>", factoryLocation["nume_documento"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", factoryLocation["NOMB_PERSONA"]);
                Format(sb, "            <vram:TradeAddress><vram:StreetName><![CDATA[{0}]]></vram:StreetName></vram:TradeAddress>", factoryLocation["DIRE_PERSONA"]);
                Format(sb, "            <vram:Ubigeo>{0}</vram:Ubigeo>", factoryLocation["id_ubigeo"]);
                Format(sb, "            <vram:TelephoneUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:TelephoneUniversalCommunication>", factoryLocation["telf_fijo"]);
                Format(sb, "            <vram:FaxUniversalCommunication><vram:CompleteNumber>{0}</vram:CompleteNumber></vram:FaxUniversalCommunication>", factoryLocation["telf_fax"]);
                Format(sb, "            <vram:EmailUniversalCommunication><vram:UniformResourceIdentifier><![CDATA[{0}]]></vram:UniformResourceIdentifier></vram:EmailUniversalCommunication>", factoryLocation["telf_fax"]);
                Format(sb, "            <vram:LegalRepresentativeIdentificationType>{0}</vram:LegalRepresentativeIdentificationType>", factoryLocation["rep_id_tipodocu"]);
                Format(sb, "            <vram:LegalRepresentativeIdentification>{0}</vram:LegalRepresentativeIdentification>", factoryLocation["rep_nume_documento"]);
                Format(sb, "            <vram:LegalRepresentativeName><![CDATA[{0}]]></vram:LegalRepresentativeName>", factoryLocation["rep_nomb_persona"]);
                Format(sb, "        </vram:TradeParty>");
                Format(sb, "    </FactoryLocation>");
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void DGS009_N8_StorageLocation(StringBuilder sb, DbDataReader storageLocation)
        {
            try
            {
                storageLocation.Read();
                Format(sb, "    <StorageLocation>");
                Format(sb, "        <vram:TradeParty><vram:Type>{0}</vram:Type></vram:TradeParty>", storageLocation["ID_SUBTIPOPERSONA"]);
                Format(sb, "        <vram:FileNumber>{0}</vram:FileNumber>", storageLocation["expplant"]);
                Format(sb, "        <vram:Resolution>{0}</vram:Resolution>", storageLocation["resolplant"]);               
                Format(sb, "    </StorageLocation>");

            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void DGS009_N8_FoodIndustrialProduct(StringBuilder sb, DbDataReader products)
        {
            string detalle;
            string[] rowSeparator = new string[] { "<->" };
            string[] colSeparator = new string[] { "]]" };
            string[] rows;
            string[] cols;

            while (products.Read())
            {
                Format(sb, "    <FoodIndustrialProduct>");
                Format(sb, "        <vram:ItemProduct>{0}</vram:ItemProduct>", products["NUME_ITEM"]);
                Format(sb, "        <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_PRODUCTO"]);
                Format(sb, "        <vram:BrandName><![CDATA[{0}]]></vram:BrandName>", products["MARC_PRODUCTO"]);

                // Composition
                detalle = (string)products["composicion"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:Composition>");
                        Format(sb, "            <vram:ItemComposition>{0}</vram:ItemComposition>", cols[0]);
                        Format(sb, "            <vram:Description><![CDATA[{0}]]></vram:Description>", cols[1]);
                        Format(sb, "        </vram:Composition>");
                    }
                }

                // LogisticsPackage
                detalle = (string)products["envase"];
                if (!string.IsNullOrEmpty(detalle))
                {
                    rows = detalle.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string row in rows)
                    {
                        cols = row.Split(colSeparator, StringSplitOptions.None);
                        Format(sb, "        <vram:LogisticsPackage>");
                        Format(sb, "            <vram:ItemPackage>{0}</vram:ItemPackage>", cols[0]);
                        Format(sb, "            <vram:Type><![CDATA[{0}]]></vram:Type>", cols[1]);
                        Format(sb, "            <vram:Material><![CDATA[{0}]]></vram:Material>", cols[2]);
                        Format(sb, "            <vram:Capacity><![CDATA[{0}]]></vram:Capacity>", cols[3]);
                        Format(sb, "        </vram:LogisticsPackage>");
                    }
                }

                Format(sb, "        <vram:LifePeriod><![CDATA[{0}]]></vram:LifePeriod>", products["PERI_VIDA"]);
                Format(sb, "        <vram:ProductIdentificationSystem><![CDATA[{0}]]></vram:ProductIdentificationSystem>", products["SIST_LOTE"]);
                Format(sb, "        <vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "                <vram:RegisterIdentifier><![CDATA[{0}]]></vram:RegisterIdentifier>", products["AUTO_SANITARIA"]);
                Format(sb, "        </vram:SanitaryRegistryOriginProductRegisterData>");
                Format(sb, "        <vram:TradeProduct>");
                Format(sb, "            <vram:TariffCode>{0}</vram:TariffCode>", products["ID_SUBPARTIDA"]);
                Format(sb, "            <vram:TariffCodeSubGroup>{0}</vram:TariffCodeSubGroup>", products["CODI_PARTIDA"]);
                Format(sb, "        </vram:TradeProduct>");
                Format(sb, "        <vram:ProductClassification>");
                Format(sb, "            <vram:Code>{0}</vram:Code>", products["CODI_CLAS"]);
                Format(sb, "            <vram:Name><![CDATA[{0}]]></vram:Name>", products["NOMB_CLASIFICACION"]);
                Format(sb, "            <vram:Group>{0}</vram:Group>", products["CODI_GRUPO"] == null ? "" : products["CODI_GRUPO"].ToString().Trim());
                Format(sb, "        </vram:ProductClassification>");
                Format(sb, "        ");

                Format(sb, "    </FoodIndustrialProduct>");
            }
        }

        private void DGS009_N8_AttachedDocument(StringBuilder sb, string folder, string filter)
        {
            string[] files = UploadHelper.ListFilesString(folder, filter);
            for (int i = 0; i < files.Length; i++)
            {
                Format(sb, "    <AttachedDocument>");
                Format(sb, "        <vram:AttachedName><![CDATA[{0}]]></vram:AttachedName>", files[i]);
                Format(sb, "    </AttachedDocument>");
            }
        }

        /*FIN DE LA MODIFICACION */



        internal void N36(JSONObject traza, decimal? idnotificacion)
        {
            string rutanueva = (string)traza["numeorden"];
            //string numeorden = (string)traza["numeorden"];
            string numeorden = rutanueva.Substring(1,10).ToString() + "\\" + rutanueva.Substring(0,11).ToString();
            string path = UploadHelper.GetPath(numeorden, null, null);
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));

            DateTime? fi = Utils.parseDate((string)traza["fechaingreso"]);
            DateTime? fs = Utils.parseDate((string)traza["fechasalida"]);

            StringBuilder sb = new StringBuilder();
            Format(sb, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            Format(sb, "<trazabilidad xsi:schemaLocation=\"Trazabilidad-1.0 Trazabilidad-1.0.xsd\" ");
            Format(sb, "       xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"Trazabilidad-1.0\" >");
            Format(sb, "    <area><![CDATA[{0}]]></area>", traza["area"]);
            Format(sb, "    <subArea><![CDATA[{0}]]></subArea>", traza["subarea"]);
            Format(sb, "    <responsable><![CDATA[{0}]]></responsable>", traza["responsable"]);
            Format(sb, "    <fechaIngreso>{0}</fechaIngreso>", fi != null ? fi.Value.ToString("yyyy-MM-dd") : "");
            Format(sb, "    <fechaEstimadaSalida>{0}</fechaEstimadaSalida>", fs != null ? fi.Value.ToString("yyyy-MM-dd") : "");
            Format(sb, "    <detalle><![CDATA[{0}]]></detalle>", traza["mensaje"]);
            Format(sb, "</trazabilidad>");

            // Generar el XML
            StreamWriter sw = File.CreateText(UploadHelper.GetPath(numeorden, null, idnotificacion.ToString() + ".xml"));
            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();

            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }



        internal void N66(string numesuce, decimal? idnotificacion, decimal? tasa, string motivo)
        {
            string path = UploadHelper.GetPath(numesuce, null, null);
            File.Delete(Path.Combine(path, idnotificacion + ".xml"));
            File.Delete(Path.Combine(path, idnotificacion + ".xml.zip"));

            StringBuilder sb = new StringBuilder();
            Format(sb, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
            Format(sb, "<requerimientoPago xmlns=\"RequerimientoPago-1.0\" ");
            Format(sb, "                   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            Format(sb, "				   xsi:schemaLocation=\"RequerimientoPago-1.0 RequerimientoPago-1.0.xsd\">");
            Format(sb, "   <tasa>{0}</tasa>", tasa);
            Format(sb, "   <codigoMotivo>{0}</codigoMotivo>", 1);
            Format(sb, "   <motivo><![CDATA[{0}]]></motivo>", motivo);
            Format(sb, "</requerimientoPago>");

            // Generar el XML
            StreamWriter sw = File.CreateText(Path.Combine(path, idnotificacion.ToString() + ".xml"));
            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();

            Compresion.ComprimirArchivos(Path.Combine(path, idnotificacion + ".xml.zip"), new string[] { Path.Combine(path, idnotificacion + ".xml") });

        }
    }
}
